class Solution
{
public:
    int mostFrequent(vector<int> &nums, int key)
    {
        int n = nums.size();
        unordered_map<int, int> targetCount;
        for (int i = 0; i < n - 1; ++i)
        {
            if (nums[i] == key)
            {
                ++targetCount[nums[i + 1]];
            }
        }
        int maxFreq = 0;
        int target = 0;
        for (auto &[t, freq] : targetCount)
        {
            if (freq > maxFreq)
            {
                target = t;
                maxFreq = freq;
            }
        }
        return target;
    }
};